//
//  NSAttributedString+Emotion.swift
//  WQEmojiKeyboard-swift
//
//  Created by Xiang on 2021/5/22.
//

import Foundation
import UIKit

extension NSAttributedString{
    
    //将富文本转为普通文本的字符串
    func mgo_getPlainString() -> String {
        var sourceString : String = self.string
        var index : Int = 0
        //遍历字符串，查找attachment类型
        self.enumerateAttribute(NSAttributedString.Key.attachment, in: NSRange.init(location: 0, length: self.string.count), options: NSAttributedString.EnumerationOptions(rawValue: 0)) { (value, range, stop) in
            if value is EmotionTextAttachment {
                //print("range="+"\(range)");
                let attachment : EmotionTextAttachment = value as! EmotionTextAttachment
                let nsRange : NSRange = NSRange.init(location: range.location+index, length: range.length)
                let range : Range = sourceString.range(from: nsRange)!
                sourceString.replaceSubrange(range, with: attachment.emotionStr)
                index += attachment.emotionStr.count - 1
            }
            
        }
        return sourceString
    }
}

extension String{
    /// NSRange转化为range
    func range(from nsRange: NSRange) -> Range<String.Index>? {
        guard
            let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex),
            let to16 = utf16.index(from16, offsetBy: nsRange.length, limitedBy: utf16.endIndex),
            let from = String.Index(from16, within: self),
            let to = String.Index(to16, within: self)
        else { return nil }
        return from ..< to
    }
}
